﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Argotic.Syndication;
using System.Net;
using System.Xml;

namespace PeapodCatcher
{
    /// <summary>
    /// Interaction logic for AddFeed.xaml
    /// </summary>
    public partial class AddFeed : Window
    {
        public delegate void FeedAdded(Object sender, FeedEventArgs e);
        public event FeedAdded OnFeedAdded;

        public AddFeed()
        {
            InitializeComponent();
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            string error = "";
            RssFeed rss = null;
            try
            {
                rss = RssFeed.Create(new Uri(url.Text));
            }
            catch (FormatException)
            {
                error = "No valid RSS streams found";
            }
            catch (XmlException)
            {
                error = "No valid RSS streams found";
            }
            catch (WebException)
            {
                error = "Invalid URL";
            }

            // simple, naive error handling
            if (!String.IsNullOrEmpty(error))
            {
                MessageBox.Show(error);
                return;
            }

            bool isMediaFly = (url.Text.ToLower().Contains("mediafly"));

            Feed feed = new Feed()
            {
                ID = Guid.NewGuid(),
                Url = url.Text,
                Title = rss.Channel.Title,
                KeepAtMost = 5,
                KeepForDays = 3,
                ParseMediaFlyShows = isMediaFly,
                Push = true,
                RemoveAfterDays = 7,
                SubPathName = Common.SafeFileName(rss.Channel.Title),
                UseSubPath = !isMediaFly,
            };

            if (OnFeedAdded != null) {
                OnFeedAdded(this, new FeedEventArgs(feed));
            }

            this.Close();
        }
    }

    public class FeedEventArgs : EventArgs {
        public FeedEventArgs(Feed feed) {
            ModifiedFeed = feed;
        }
        public Feed ModifiedFeed { get; set; }
    }

}
